package utils;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import corp.CardAccount;
import corp.ControlAccount;
import corp.Corporation;
import corp.ServiceResponse;

public class CorporateDAO {
	
	final String host;
	final HttpClient client = new HttpClient();
	
	public CorporateDAO(final String host){
		this.host = host;
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
				  new DefaultHttpMethodRetryHandler());
	}
	
	
	public ServiceResponse<Corporation> getCorporation(final String id) throws HttpException, IOException{
		final HttpClient client = new HttpClient();
		final HttpMethod method = new GetMethod(host + "/corp/corpservice.json?function=GetCorpByID&corpID=" + id);
		client.executeMethod(method);
		final String json = method.getResponseBodyAsString();
		method.releaseConnection();
		System.out.print(json);
		return new Gson().fromJson(json, new TypeToken<ServiceResponse<Corporation>>(){}.getType());		
	}
	
	public ServiceResponse<ControlAccount> addCtrlAccount(final String id, final String ctrl) throws HttpException, IOException{
		final HttpClient client = new HttpClient();
		final HttpMethod method = new PostMethod(host + "/corp/corpservice.json?function=addCtrl&corpID="+id+",&newCtrlID="+ctrl);
		client.executeMethod(method);
		final String json = method.getResponseBodyAsString();
		method.releaseConnection();
		System.out.print(json);
		return new Gson().fromJson(json, new TypeToken<ServiceResponse<ControlAccount>>(){}.getType());
	}

}
